<?php
	require_once('paths.inc');
	require_once(INCLUDE_PATH.'constants.inc');
	require_once('page.inc');
	require_once(DB_PATH.'db.inc');
	
	require_once('security.inc');
	require_once('utils.inc');	
	require_once('time.inc');
		
	session_start();		
	check_permissions(CT_PERM_EDIT_CLIENT);
			
	$id_client = $_SESSION['user_logat']->id_client;
		
	$db = db_connect();
    
	if (isset($_POST['comit'])) {
		//logoul tratat aici						
		
		$fn = basename($_FILES['file']['name']);
		$ext = explode('.', $fn); 
		$extension = $ext[count($ext)-1];
		$nume_fis = '';
		$remove_banner = false;
		
		if ($_FILES['file']['size'] < CT_MAX_UPLOAD_FILE_SIZE && (strtolower($extension)=='jpg' || strtolower($extension)=='jpeg' 
																		|| strtolower($extension)=='png' || strtolower($extension)=='gif')) {
			$nume_fis = $id_client . '.' . strtolower($extension);

			$temp_name = $_FILES['file']['tmp_name'];
			if (is_uploaded_file($temp_name)) {
				system("rm -f " . FULL_IMAGE_PATH . $_SESSION['setari']->cale_banner . " > /dev/null", $ret_val);
				move_uploaded_file($temp_name, FULL_IMAGE_PATH . "images/client_banners/" . $nume_fis);	
				
				/*
				 * voi muta poza in folderul de comanda odt dezpachetat pentru fiecare user al clientului respectiv
				 */
						  
				try {
					$users = User::queryLoadByClient($db, $_SESSION['user_logat']->id_client, true, $_SESSION['client_logat']->admin_user_id);
				}
				catch (QueryLoadUserException $e) {
					redirectOnError(CT_ADD_USERS_LOAD_USER);
				}	
				
				foreach ($users as $user_curent) {
					system("cp -f " . CLIENT_BANNERS_FULL_PATH . "$nume_fis " . USERS_PATH . $user_curent->id_user . "/comanda_dez/Pictures/$nume_fis > /dev/null", $ret_val);
				}
			}
			else 
				redirectOnError(CT_ERROR_UPLOADING_FILE);
		}
		else if ($_POST['remove_banner'] == "1") {
			$remove_banner = true;
		}
		
		$termeni = $_POST['termeni'];
		//$antet_mail = $_POST['antet_mail'];

		$zile_scadenta_sol = $_POST['zile_scadenta_sol'];	
		$zile_scadenta_exec = $_POST['zile_scadenta_exec'];	
		$zile_alarma_plati = $_POST['zile_alarma_plati'];	
		$zile_alarma_incasari = $_POST['zile_alarma_incasari'];	
		
		$zile_alarma_incarcari = $_POST['zile_alarma_incarcari'];
		$zile_alarma_descarcari = $_POST['zile_alarma_descarcari'];
		
		//server side validations
		$_SESSION['wrong_ids'] = array();
			
		if ($nume_fis != '')       
		    $cale_banner = "images/client_banners/" . $nume_fis;
            
		$setari = $_SESSION['setari'];
        
        //$setari->antet_mail = $antet_mail;
        
        if ($nume_fis != '')
            $setari->cale_banner = $cale_banner;
        
        $rez = strpos($setari->termeni, '<p align="left">&nbsp;</p>');
        if ( $rez === false || $rez != 0)
            $setari->termeni = '<p align="left">&nbsp;</p>' . $termeni;
        
        if ($remove_banner) {
			unlink($setari->cale_banner);
			$setari->cale_banner = '';		
		}
		
        $aux = filter_var($zile_alarma_incarcari, FILTER_VALIDATE_INT);
		if ($aux === false) {
			$_SESSION['wrong_ids']['zile_alarma_incarcari'] = 1;
		}
		$setari->zile_alarma_incarcari = $zile_alarma_incarcari;
		
        $aux = filter_var($zile_alarma_descarcari, FILTER_VALIDATE_INT);
		if ($aux === false) {
			$_SESSION['wrong_ids']['zile_alarma_descarcari'] = 1;
		}
		$setari->zile_alarma_descarcari = $zile_alarma_descarcari;		
		       
        $aux = filter_var($zile_alarma_incasari, FILTER_VALIDATE_INT);
		if ($aux === false) {
			$_SESSION['wrong_ids']['zile_alarma_incasari'] = 1;
		}
		$setari->zile_alarma_incasari = $zile_alarma_incasari;
			
        $aux = filter_var($zile_alarma_plati, FILTER_VALIDATE_INT);
		if ($aux === false) {
			$_SESSION['wrong_ids']['zile_alarma_plati'] = 1;
		}	
		$setari->zile_alarma_plati = $zile_alarma_plati;
			
        $aux = filter_var($zile_scadenta_exec, FILTER_VALIDATE_INT);
		if ($aux === false) {
			$_SESSION['wrong_ids']['zile_scadenta_exec'] = 1;
		}
		$setari->zile_scadenta_exec = $zile_scadenta_exec;
			
        $aux = filter_var($zile_scadenta_sol, FILTER_VALIDATE_INT);
		if ($aux === false) {
			$_SESSION['wrong_ids']['zile_scadenta_sol'] = 1;
		}
		$setari->zile_scadenta_sol = $zile_scadenta_sol;

		//end verificari serverside         
		if (count($_SESSION['wrong_ids']) > 0) {
			error_msg($mesaj_aditional . LANG_Campurile_rosii_trebuiesc_completate_corect, 'opt_generale.php');
		}
        
		try {
			$setari->queryUpdateSetariClient($db);
			
			/*
			 * urmeaza sa salvam termenii si conditiile intr-un fisier nume.html pentru
			 * a putea fi introdus in printarea comenzilor
			 */
			
			file_put_contents(USERS_PATH . $_SESSION['user_logat']->id_user . "/termeni.html", stripslashes($termeni));
            // TODO: go to some page...
            notice_msg(LANG_Optiunile_au_fost_salvate, 'home.php');
		}
		catch (QuerySettingsNotExistException $e) {
			try {
				$setari->queryInsertSetariClient($db);
			}
			catch (QueryInsertSetariException $e) {
				redirectOnError(CT_OPT_GEN_INSERT_SETARI);
			}
		}
		catch (QueryLoadSetariException $e) {
			redirectOnError(CT_OPT_GEN_LOAD_SETARI);
		}
		catch (QueryUpdateStareException $e) {
			redirectOnError(CT_OPT_GEN_UPDATE_SETARE_EXCEPTION);
		}
	}
    else {
        html_header("LANG_Optiuni_Generale", null, "opt_generale");
        include_js('tinymce/jscripts/tiny_mce/tiny_mce.js');
?>

<script language="javascript" type="text/javascript">
tinyMCE.init({
    mode                            : "exact",
    elements                        : "termeni",
    theme                           : "advanced",
    theme_advanced_buttons1         : "bold,italic,underline,fontselect,fontsizeselect,|,justifyleft,justifycenter,justifyright,justifyfull",
    theme_advanced_buttons2         : "",
    theme_advanced_buttons3         : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align    : "left"
});
    // Custom event handler
    function myCustomExecCommandHandler(editor_id, elm, command, user_interface, value) {
        var linkElm, imageElm, inst;

        switch (command) {
            case "mceLink":
                inst = tinyMCE.getInstanceById(editor_id);
                linkElm = tinyMCE.getParentElement(inst.selection.getFocusElement(), "a");

                if (linkElm)
                    alert("Link dialog has been overriden. Found link href: " + tinyMCE.getAttrib(linkElm, "href"));
                else
                    alert("Link dialog has been overriden.");

                return true;

            case "mceImage":
                inst = tinyMCE.getInstanceById(editor_id);
                imageElm = tinyMCE.getParentElement(inst.selection.getFocusElement(), "img");

                if (imageElm)
                    alert("Image dialog has been overriden. Found image src: " + tinyMCE.getAttrib(imageElm, "src"));
                else
                    alert("Image dialog has been overriden.");

                return true;
        }

        return false; // Pass to next handler in chain
    }

    // Custom save callback, gets called when the contents is to be submitted
    function customSave(id, content) {
        alert(id + "=" + content);
    }

    function validateForm() {								
		return (validatePosInteger(document.opt_generale.zile_scadenta_sol.value, '<?php echo LANG_Zile_scadenta_sol; ?>', true) &&
			validatePosInteger(document.opt_generale.zile_scadenta_exec.value, '<?php echo LANG_Zile_scadenta_exec; ?>', true) &&
			validatePosInteger(document.opt_generale.zile_alarma_plati.value, '<?php echo LANG_Zile_alarma_plati; ?>', true) &&
			validatePosInteger(document.opt_generale.zile_alarma_incasari.value, '<?php echo LANG_Zile_alarma_incasari; ?>', true) &&
			validatePosInteger(document.opt_generale.zile_alarma_incarcari.value, '<?php echo LANG_Zile_alarma_incasari; ?>', true) &&
			validatePosInteger(document.opt_generale.zile_alarma_descarcari.value, '<?php echo LANG_Zile_alarma_incasari; ?>', true));
	}
		
</script>
        
<?php
    $linkuri = array(LANG_Home => "home.php", LANG_Optiuni_Generale => "");
    titlu_pagina($linkuri);
    output_notice_msg();
    output_error_msg();
    output_extra_text(LANG_EXTRA_OPT_GENERALE);
    
        // Init setari object
        
        try {
            $setari = SetariClient::queryLoadSetariClient($db, $id_client);            
        }
        catch (QueryLoadSetariException $e) {
            redirectOnError(CT_OPT_GEN_LOAD_SETARI);
        }
        catch (QuerySettingsNotExistException $e) {
            redirectOnError(CT_OPT_GEN_NO_EXIST);
        }
//        $setari = new SetariClient($id_client, '', '', '', 30, 45, 7, 7);
        $_SESSION['setari'] = $setari;
	    for ($i = 0; $i < count($currencies); $i++) $monedaValues[] = $i; ?>
	    <div align="left" class="container">
	    	<table align="left" id="wrapper2">
		     	<form method="post" name="opt_generale" enctype="multipart/form-data" action="opt_generale.php" onsubmit="return (validateForm());">
			     <thead>
				     <tr>
					     <th colspan="4" align="center"><?php echo LANG_Optiuni_Generale; ?></th>
				     </tr>
			     </thead>
			     <tr class="capTabel">
				     <td><?php echo LANG_Image_Logo; ?></td>
				     <td colspan="3" valign="bottom">
					     <input type="file" name="file" <?php echo show_tooltip(LANG_opt_generale_image_logo_tooltip); ?> />
                         <br />
                         
                         <?php 
                            if (!empty($setari->cale_banner)) {
								echo '<div id="image">
										<table width="100%">
											<tr><td align="right" width="151">';
                                echo "<img width=\"300\" src=\"{$setari->cale_banner}\" />";
                                echo '</td><td align="left" valign="center">';
                                echo '<a onClick="document.opt_generale.remove_banner.value=\'1\';
										document.getElementById(\'image\').style.display  = \'none\'; ">'.LANG_Sterge_poza.'</a>';
								echo '</td></tr></table>
										</div>';
                            }
                         ?>				
                         
				     </td>
			     </tr>
			     <!--
			     <tr class="capTabel">
				     <td><?php echo LANG_Antet_mail; ?></td>
				     <td colspan="3">
					     <textarea <?php echo show_tooltip(LANG_opt_generale_antet_mail_tooltip); ?> name="antet_mail" cols="66" rows="5" maxlength="<?php echo CT_MAX_ANTET_MAIL; ?>"><?php echo $setari->antet_mail; ?></textarea>
				     </td>
			     </tr>
			     -->
			     <tr class="capTabel">
				     <td <?php check_field('zile_scadenta_sol'); ?>><?php echo LANG_Zile_scadenta_sol; ?></td>
				     <td>
				 	    <input value="<?php echo $setari->zile_scadenta_sol; ?>" <?php echo show_tooltip(LANG_opt_generale_Zile_scadenta_sol_tooltip); ?> type="text" size="2" maxlength="<?php echo CT_MAX_NR_ZILE; ?>" name="zile_scadenta_sol" />
				     </td>
				     <td  <?php check_field('zile_scadenta_exec'); ?> width="190"><?php echo LANG_Zile_scadenta_exec; ?></td>
				     <td>
				 	    <input value="<?php echo $setari->zile_scadenta_exec; ?>" <?php echo show_tooltip(LANG_opt_generale_Zile_scadenta_exec_tooltip); ?> type="text" size="2" maxlength="<?php echo CT_MAX_NR_ZILE; ?>" name="zile_scadenta_exec" />
				     </td>
			     </tr>
			     <tr class="capTabel">
				     <td  <?php check_field('zile_alarma_plati'); ?> align="left"><?php echo LANG_Zile_alarma_plati; ?></td>
				     <td>
				 	    <input value="<?php echo $setari->zile_alarma_plati; ?>" <?php echo show_tooltip(LANG_opt_generale_Zile_alarma_plati_tooltip); ?> type="text" size="2" maxlength="<?php echo CT_MAX_NR_ZILE; ?>" name="zile_alarma_plati" />
				     </td>
				     <td  <?php check_field('zile_alarma_incasari'); ?>><?php echo LANG_Zile_alarma_incasari; ?></td>
				     <td>
				 	    <input value="<?php echo $setari->zile_alarma_incasari; ?>" <?php echo show_tooltip(LANG_opt_generale_Zile_alarma_incasari_tooltip); ?> type="text" size="2" maxlength="<?php echo CT_MAX_NR_ZILE; ?>" name="zile_alarma_incasari" />
				     </td>
			     </tr>
			     <tr class="capTabel">
				     <td <?php check_field('zile_alarma_incarcari'); ?> align="left"><?php echo LANG_Zile_alarma_incarcari; ?></td>
				     <td>
				 	    <input value="<?php echo $setari->zile_alarma_incarcari; ?>" <?php echo show_tooltip(LANG_opt_generale_Zile_alarma_incarcari_tooltip); ?> type="text" size="2" maxlength="<?php echo CT_MAX_NR_ZILE; ?>" name="zile_alarma_incarcari" />
				     </td>
				     <td <?php check_field('zile_alarma_descarcari'); ?>><?php echo LANG_Zile_alarma_descarcari; ?></td>
				     <td>
				 	    <input value="<?php echo $setari->zile_alarma_descarcari; ?>" <?php echo show_tooltip(LANG_opt_generale_Zile_alarma_descarcari_tooltip); ?> type="text" size="2" maxlength="<?php echo CT_MAX_NR_ZILE; ?>" name="zile_alarma_descarcari" />
				     </td>
			     </tr>			     
			     <tr class="capTabel">
				     <td><?php echo LANG_Termeni_si_conditii_transport; ?></td>
				     <td colspan="3">
				 	    <textarea <?php echo show_tooltip(LANG_opt_generale_temeni_cond_tooltip); ?> name="termeni" cols="80" rows="25"><?php echo $setari->termeni; ?></textarea>
				     </td>	
			     </tr>
			     <tr class="capTabel">
				     <td colspan="4" align="center">
					    <?php
						    buton_final_ok(LANG_Save_Options, "comit"); 
					 	    echo "&nbsp;&nbsp;";
						    buton_final_cancel(LANG_Cancel, "home.php"); 						
					    ?>
				     </td>
			     </tr>
			     <input type="hidden" name="remove_banner" value="0">
			     </form>
		     </table>
	     </div>
<?php
    }
	unset($_SESSION['wrong_ids']);	
	html_footer();
?>